import { useRef } from 'react';
import { getDirection } from './util';

export type Direction = '' | 'vertical' | 'horizontal';

export function useTouch() {
    const touchRef = useRef({
        startX: 0,
        startY: 0,
        deltaX: 0,
        deltaY: 0,
        delta: 0,
        offsetX: 0,
        offsetY: 0,
        direction: '',
        last: false,
        velocity: 0,
        touchTime: Date.now()
    });

    const isVertical = () => touchRef.current.direction === 'vertical';
    const isHorizontal = () => touchRef.current.direction === 'horizontal';

    const reset = () => {
        touchRef.current.touchTime = Date.now();
        touchRef.current.deltaX = 0;
        touchRef.current.deltaY = 0;
        touchRef.current.offsetX = 0;
        touchRef.current.offsetY = 0;
        touchRef.current.delta = 0;
        touchRef.current.direction = '';
        touchRef.current.last = false;
    };

    const start = (event: React.TouchEvent<HTMLElement>) => {
        reset();
        console.log('日志----start');
        touchRef.current.touchTime = Date.now();
        touchRef.current.startX = event.touches[0].clientX;
        touchRef.current.startY = event.touches[0].clientY;
    };

    const move = (event: React.TouchEvent<HTMLElement>) => {
        const touch = event.touches[0];

        touchRef.current.deltaX = touch.clientX < 0 ? 0 : touch.clientX - touchRef.current.startX;
        touchRef.current.deltaY = touch.clientY - touchRef.current.startY;
        touchRef.current.offsetX = Math.abs(touchRef.current.deltaX);
        touchRef.current.offsetY = Math.abs(touchRef.current.deltaY);
        if (!touchRef.current.direction) {
            touchRef.current.direction = getDirection(
                touchRef.current.offsetX,
                touchRef.current.offsetY
            );
        }

        touchRef.current.delta = isVertical() ? touchRef.current.deltaY : touchRef.current.deltaX;
    };
    const end = () => {
        touchRef.current.last = true;
        touchRef.current.direction = '';
        touchRef.current.velocity =
            Math.sqrt(touchRef.current.deltaX ** 2 + touchRef.current.deltaY ** 2) /
            (Date.now() - touchRef.current.touchTime);
    };

    return {
        end,
        move,
        start,
        reset,
        touchRef,
        isVertical,
        isHorizontal
    };
}
